<?php

namespace App\Http\Controllers\Otc;

use App\DesignPatterns\Strategy\RechOrderCollection;
use App\Http\Controllers\Controller;
use App\Models\Appeal;
use App\Models\AppealImg;
use App\Models\AppealReply;
use App\Models\AppealReplyImg;
use App\Models\Recharge;
use App\Models\User;
use App\Models\Message;
use App\Models\Operate;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 订单管理.
 */
class OrderController extends Controller
{
    /**
     * 修改订单状态
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_order_status(Request $request)
    {
        //验证必传参数
        if (!$request->has('uid', 'rid', 'status')) {
            //错误提示
            return respF(1003);
        }
        //用户id
        $uid = $request->get('uid');
        //查找用户
        $user = User::find($uid);
        //验证用户
        if (!$user) {
            //用户不存在
            return respF(1001);
        }
        //订单id
        $rid = $request->get('rid');
        //查找订单
        $rech = Recharge::find($rid);
        //未找到
        if (!$rech) {
            //订单不存在
            return respF(1002);
        }
        //状态值
        $status = $request->get('status');
        //验证状态值
        if (!in_array($status, [2, 3, 4])) {
            //状态值错误
            return respF(3003);
        }

        //如果是确认发币
        if ($status == 3) {
            //验证交易密码
            $pay_pass = $request->get('pay_pass');
            //判断交易密码
            if ($user->pay_pass != md5($pay_pass)) {
                //错误提示
                return respF(2000);
            }
        }
        //策略模式执行订单修改状态
        $obj = new RechOrderCollection($status, $uid, $rid);
        //执行
        return $obj->entry();
    }

    /**
     * 申诉订单.
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function appeal_order(Request $request)
    {
        try {
            //验证必传参数
            if (!$request->has('uid', 'rid', 'type', 'content')) {
                //错误提示
                throw new Exception(1003);
            }
            //申诉人id
            $uid = $request->get('uid');
            //订单id
            $rid = $request->get('rid');
            //申诉类型
            $type = $request->get('type');
            //内容
            $content = $request->get('content');
            //图片
            $photo = $request->get('photo');
            //查找订单
            $rech = Recharge::find($rid);
            //订单不存在
            if (collect($rech)->count() == 0) {
                throw new Exception(1027);
            }
            //订单状态为已完成或已取消的情况下，不能申述
            if ($rech->status == 3) {
                throw new Exception(4008);
            }
            //有申述订单
            if (collect($rech->appeal_order)->count() > 0) {
                //且订单为申述中
                if ($rech->appeal_order->status == 0) {
                    //且申述未过期
                    if ($rech->appeal_order->expire_time < time()) {

                        throw new Exception(4006);
                    }
                }
            } else {
                if ($rech->status != 2) {
                    throw new Exception(3003);
                }
            }
            //开启事务
            DB::beginTransaction();
            $operate = Operate::find(1);
            $value = $operate->value ?? 259200;
            $expire_time = time() + $value;
            //提交申诉内容
            $res = Appeal::create([
                'uid' => $uid,
                'rid' => $rid,
                'type' => $type,
                'content' => $content,
                'expire_time' => $expire_time,
            ]);
            //拆分头像为数组
            if ($photo) {
                $imgs = explode(',', rtrim($photo, ','));
                //dd($imgs);
                //遍历
                foreach ($imgs as $img) {
                    //修改路径-zrc 2018-5-26
                    if (strpos($img, '//')) {
                        $img_s = parse_url($img);
                        $img = ltrim($img_s['path'], '/');
                    }
                    //end 2018-5-26
                    //$img = str_replace(config('alioss.host-domain'), '', $img);
                    //写入数据库
                    AppealImg::create([
                        'aid' => $res->id,
                        'img' => $img,
                    ]);
                }                
            }

            //备份订单状态
            $backup_status = 2;
            //修改订单状态
            $rech->update(['status' => 5, 'backup_status' => $backup_status]);
            //申述类型
            $note = appealType($type);
            //写入消息(商家提交申述，向用户发送被申述通知)
            $msgArr = ['msg_id' => 22, 'uid' => $rech->uid, 'message' => [$rech->order_no, $note],"arr"=> ['number' => $rech->id]];
            (new Message())->syspublishsmsAll($msgArr);

            //提交事务
            DB::commit();
            //成功提示
            return response()->json(['status' => 1, 'msg' => '申诉已提交']);
        } catch (Exception $e) {
            //事务回滚
            DB::rollback();
            //错误提示
            $msg = $e->getMessage();

            return respF($msg);
        }
    }

    /**
     * 回复申述.
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return [type] [description]
     */
    public function appeal_reply(Request $request)
    {
        try {
            //验证必传参数
            if (!$request->has('uid', 'appeal_id', 'content')) {
                //错误提示
                throw new Exception(1003);
            }
            //申诉人id
            $uid = $request->get('uid');
            //申述id
            $appeal_id = $request->get('appeal_id');
            //回复内容
            $content = $request->get('content');
            //回复图片
            $photo = $request->get('photo');
            //开启事务
            DB::beginTransaction();
            //查找申述单
            $appeal = Appeal::find($appeal_id);
            //判定申述是否过期
            if (time() > $appeal->expire_time) {
                //已超过3天申述期
                throw new Exception(4002);
            }     
            //订单状态必须是申述中
            $recharge = Recharge::find($appeal->rid);
            if ($recharge->status != 5) {
                throw new Exception(4007);
            }
            //申述单状态必须是0
            if ($appeal->status != 0) {
                throw new Exception(3008);
            }
            //提交申诉内容
            $res = AppealReply::create([
                'uid' => $uid,
                'appeal_id' => $appeal_id,
                'content' => $content,
            ]);
            if ($photo) {
                //拆分头像为数组
                $imgs = explode(',', rtrim($photo, ','));
                //dd(gettype($photo));
                //遍历
                foreach ($imgs as $img) {
                    //修改路径-zrc 2018-5-26
                    if (strpos($img, '//')) {
                        $img_s = parse_url($img);
                        $img = ltrim($img_s['path'], '/');
                    }
                    //end 2018-5-26
                    //写入数据库
                    AppealReplyImg::create([
                        'reply_id' => $res->id,
                        'img' => $img,
                    ]);
                }                
            }

            //修改申述单状态为已回复
            $appeal->update(['status' => 1]);
            //提交事务
            DB::commit();
            //成功提示
            return response()->json(['status' => 1, 'msg' => '申诉已提交']);
        } catch (Exception $e) {
            //事务回滚
            DB::rollback();
            //错误提示
            $msg = $e->getMessage();

            return respF($msg);
        }
    }
}
